package top.pengdong.dachuang.menu.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.pengdong.common.utils.PageUtils;
import top.pengdong.common.utils.Query;

import top.pengdong.dachuang.menu.dao.CategoryDao;
import top.pengdong.dachuang.menu.entity.CategoryEntity;
import top.pengdong.dachuang.menu.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 组装成父子的树形结构
        List<CategoryEntity> collect = categoryEntities.stream().filter((categoryEntity -> {
            return categoryEntity.getParentId() == 0;
        })).map((menu) -> {
            menu.setChildren(getChildren(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            if(menu1 == null && menu2 == null) return 0;
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());

        return collect;
    }

    // 递归查找子菜单
    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> entities) {
        List<CategoryEntity> collect = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == entity.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, entities));
            return categoryEntity;
        }).sorted((menu1,menu2) -> {
            if(menu1 == null && menu2 == null) return 0;
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检测当前节点是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }
}